//
//  PlSSIMBLManager.m
//  Injector
//
//  Created by ∞ on 13/11/07.
//  Copyright 2007 Emanuele Vulcano. All rights reserved.
//

#import "PlSSIMBLManager.h"
#import "PlSSIMBLPlugIn.h"

@implementation PlSSIMBLManager

- (id) init {
	if (self = [super init])
		plugIns = [NSMutableDictionary new];
	
	return self;
}

- (void) dealloc {
	[plugIns release];
	[super dealloc];
}

- (NSArray*) plugIns {
	return [plugIns allValues];
}

- (void) rescan {
	[plugIns removeAllObjects];
	
	NSFileManager* fm = [NSFileManager defaultManager];
	
	NSArray* libraries = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask | NSNetworkDomainMask | NSLocalDomainMask, YES);
	for (NSString* place in libraries) {
		place = [place stringByAppendingPathComponent:@"SIMBL/PlugIns"];
		BOOL isDir;
		
		if (![fm fileExistsAtPath:place isDirectory:&isDir] || !isDir)
			continue;
		
		NSArray* contents = [fm directoryContentsAtPath:place];
		for (NSString* item in contents) {
			if ([item hasPrefix:@"."]) continue;
			item = [place stringByAppendingPathComponent:item];
			
			PlSSIMBLPlugIn* pin = [PlSSIMBLPlugIn plugInWithPath:item manager:self];
			if (pin)
				[plugIns setObject:pin forKey:pin.identifier];
		}
	}
}

- (PlSPlugIn*) plugInWithIdentifier:(NSString*) ident {
	return [plugIns objectForKey:ident];
}

- (PlSInstallStatus) installPlugInAtPath:(NSString*) path andReturnError:(NSError**) error {
	PlSSIMBLPlugIn* pin = [[PlSSIMBLPlugIn alloc] initWithPath:path manager:self];
	if (!pin) return kPlSInstallIncompatible;
	[pin release]; // just to check.
	
	NSArray* arr = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
	if ([arr count] == 0) return kPlSInstallIncompatible; // TODO a real error.
	
	NSString* target = [[[arr objectAtIndex:0] stringByAppendingPathComponent:@"SIMBL/Plugins"] stringByAppendingPathComponent:[path lastPathComponent]];
	if (![[NSFileManager defaultManager] copyItemAtPath:path toPath:target error:error])
		return kPlSInstallError;
	else
		return kPlSInstallDone;
}

@end
